import React, { useEffect, useState } from "react";
import { useNavigate, useRoutes } from "react-router-dom";
import PubSub from "pubsub-js";
import router from "./router";
import { Breadcrumb, Layout, Menu, theme } from "antd";
import "@/assets/styles/App.scss";
import axios from "axios";

const { Header, Content, Footer } = Layout;

const App: React.FC = () => {
  const [current, setCurrent] = useState("/");

  let sourceitems = [
    {
      key: "/",
      label: "主页",
    },
  ];

  const [items, setItems] = useState(sourceitems);

  useEffect(() => {
    freshMenu();
  }, []);

  const freshMenu = () => {
    let i = [];
    if (
      localStorage.getItem("login_token") ||
      localStorage.getItem("login_token") != undefined
    ) {
      i = sourceitems.concat([
        {
          key: "/manager",
          label: "后台管理",
        },
        {
          key: "/logout",
          label: "退出登陆",
        },
      ]);
    } else {
      i = sourceitems.concat([
        {
          key: "/login",
          label: "登陆",
        },
        {
          key: "/register",
          label: "注册",
        },
      ]);
    }
    setItems(i);
  };

  const {
    token: { colorBgContainer },
  } = theme.useToken();

  const navigateTo = useNavigate();

  PubSub.subscribe("ChangeMenu", (path: string) => {
    setCurrent(path);
  });

  PubSub.subscribe("freshMenu", () => {
    freshMenu();
  });

  const menuClick = (e: { key: string }) => {
    setCurrent(e.key);
    navigateTo(e.key);
  };

  const outlet = useRoutes(router);

  return (
    <Layout className="layout">
      <Header>
        <Menu
          style={{ float: "right" }}
          theme="dark"
          mode="horizontal"
          defaultSelectedKeys={["2"]}
          selectedKeys={[current]}
          items={items}
          onClick={menuClick}
        />
      </Header>
      <Content
        style={{ padding: "0 50px", background: "#1c1c1c", minHeight: "800px" }}
      >
        <div
          className="site-layout-content"
          style={{ background: colorBgContainer }}
        >
          {outlet}
        </div>
      </Content>
      <Footer
        style={{ textAlign: "center", background: "#001529", color: "#fff" }}
      >
        Nothing to show
      </Footer>
    </Layout>
  );
};

export default App;
